package com.liao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liao.common.Result;
import com.liao.dto.BookDTO;
import com.liao.entity.Book;
import com.liao.service.BookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 图书控制器
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @Resource
    private BookService bookService;

    /**
     * 获取图书分页列表
     *
     * @param current    当前页
     * @param size       每页大小
     * @param name       图书名称（可选）
     * @param author     作者（可选）
     * @param categoryId 分类ID（可选）
     * @return 分页图书列表
     */
    @GetMapping("/page")
    public Result<Page<Book>> getBookPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String author,
            @RequestParam(required = false) Long categoryId) {
        Page<Book> page = new Page<>(current, size);
        Page<Book> bookPage = bookService.getBookPage(page, name, author, categoryId);
        return Result.success(bookPage);
    }

    /**
     * 获取图书详情
     *
     * @param id 图书ID
     * @return 图书详情
     */
    @GetMapping("/{id}")
    public Result<Book> getBookDetail(@PathVariable Long id) {
        Book book = bookService.getBookById(id);
        if (book == null) {
            return Result.error("图书不存在");
        }
        return Result.success(book);
    }

    /**
     * 添加图书
     *
     * @param bookDTO 图书信息
     * @return 添加结果
     */
    @PostMapping
    public Result<Boolean> addBook(@RequestBody @Valid BookDTO bookDTO) {
        boolean result = bookService.addBook(bookDTO);
        return Result.success(result);
    }

    /**
     * 修改图书
     *
     * @param id      图书ID
     * @param bookDTO 图书信息
     * @return 修改结果
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateBook(@PathVariable Long id, @RequestBody @Valid BookDTO bookDTO) {
        bookDTO.setId(id);
        boolean result = bookService.updateBook(bookDTO);
        return Result.success(result);
    }

    /**
     * 删除图书
     *
     * @param id 图书ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteBook(@PathVariable Long id) {
        boolean result = bookService.deleteBook(id);
        return Result.success(result);
    }

    /**
     * 更新图书库存
     *
     * @param id    图书ID
     * @param stock 库存数量
     * @return 更新结果
     */
    @PutMapping("/{id}/stock")
    public Result<Boolean> updateBookStock(
            @PathVariable Long id,
            @RequestParam Integer stock) {
        if (stock < 0) {
            return Result.error("库存不能小于0");
        }
        boolean result = bookService.updateBookStock(id, stock);
        return Result.success(result);
    }
}